<template>
	<div class="x-markdown">
		<alabo-editor :subfield="subfield" class="markdown-body" ref="alaboEditor" @change="changeTime" v-model="viewModel"
			:height="500" @changeImageClick="changeImageClick" @uploadImage="uploadImage" :toolbarsFlag="toolbarsFlag">
		</alabo-editor>
		<el-dialog :visible="dialogVisible" top="8vh" :before-close="handleClose" :append-to-body="true">
			<zk-file-manage @autoDialogClose="handleClose" @selectFileChildEvent="selectFileChildEvent"></zk-file-manage>
		</el-dialog>
		<alaUpload ref="alaUpload"></alaUpload>
	</div>
</template>


<script>
import {
	alaboEditor
} from 'alabo-editor'
import 'alabo-editor/dist/css/index.css'
import ala from 'ala'
import alaUpload from './upload'
export default {
	model: {
		prop: 'dataModel',
		event: 'change'
	},
	props: {
		dataModel: {},
		toolbarsFlag: { // 是否开启工具栏
			type: Boolean,
			default: true
		},
		subfield: {
			type: Boolean,
			default: true
		} // 分栏显示，默认为true
	},
	data() {
		return {
			viewModel: '',
			dialogVisible: false
		}
	},
	components: {
		alaboEditor,
		alaUpload
	},
	mounted() {
		this.init()
	},
	methods: {
		init(data) {
			if (data) {
				this.viewModel = data
			} else {
				if (this.dataModel) {
					this.viewModel = this.dataModel
				}
			}
			this.$forceUpdate()
		},
		// 自定义上传图片啊
		changeImageClick() {
			var file = {
				_name: 'image.png'
			}
			this.dialogVisible = true
		},
		// 监听编辑器复制功能
		async uploadImage(data) {
			var storageFile = await this.$ala.uploadCopyImage(data)
			this.$nextTick(() => {
				if (this.$refs.alaboEditor) {
					var imageImage = {
						file: {
							_name: storageFile.name
						},
						image: ala.urlImage(storageFile.path)
					}
					this.$refs.alaboEditor.uploadedImage(imageImage)
				}
			})
		},
		changeTime(e) {

		},
		handleClose() {
			this.dialogVisible = false
		},
		selectFileChildEvent(data) {
			var image = ala.host + data.path
			if (data.path.substring(0, 1) === '/') {
				image = ala.host + data.path.substring(1)
			}
			var file = {
				_name: 'image.png'
			}
			this.$refs.alaboEditor.uploadedImage({
				file,
				image
			})
			this.handleClose()
		}
	},
	watch: {
		viewModel: {
			deep: true,
			handler(val) {
				this.$emit('change', this.viewModel)
			}
		}
	}
}
</script>


<style lang="scss">
@import "./markdown.scss";
</style>